<template>
  <div class="cities-searcher">
    <input type="text" v-model.trim="searchText" placeholder="请输入城市名称" @input="searchCity" />
    <ul v-if="searchUlShow">
      <li v-for="city in cities" @click="handleClick(city)">{{ city.name }}</li>
      <p v-if="ulStatus === 'noCityFound'">似乎没有找到你查找的城市</p>
      <p v-if="ulStatus === 'networkError'">对不起网络似乎出了点问题 请稍后再查询</p>
    </ul>
  </div>
</template>

<script setup>
import { useWeatherStore } from '@/stores/weather'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'

const { searchCity } = useWeatherStore()
const { searchText, cities, ulStatus, searchUlShow, selectedCity } = storeToRefs(useWeatherStore())
const router = useRouter()

const handleClick = (city) => {
  selectedCity.value = city.name
  const path = `/${city.adcode}?search=${city.name}`
  router.push(path)
  searchText.value = ''
  searchUlShow.value = false
  ulStatus.value = '1'
}
</script>

<style lang="scss" scoped>
$box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1);
.cities-searcher {
  position: relative;
  margin-bottom: 32px;
  padding-top: 16px;

  input {
    width: 100%;
    padding: 8px 4px;
    font-size: 16px;
    line-height: 24px;
    color: white;

    background-color: rgb(0, 102, 138);
    border: none;
    border-bottom: 1px solid rgb(229, 231, 235);

    &::placeholder {
      color: rgb(157, 163, 175);
    }

    &:focus {
      outline: 2px solid transparent;
      border-bottom: 1px solid rgb(0, 78, 113);
      box-shadow: $box-shadow;
    }
  }
  ul {
    position: absolute;
    top: 62px;
    width: 100%;
    padding: 8px 4px;
    list-style: none;
    color: white;
    background-color: rgb(0, 78, 113);
    box-shadow: $box-shadow;

    p {
      line-height: 24px;
    }

    li {
      line-height: 24px;
      padding: 8px 0;
      cursor: pointer;
    }
  }
}
</style>
